package com.onenine.app.fragment;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.onenine.app.R;
import com.onenine.app.activity.AskInviteListActivity;
import com.onenine.app.activity.DynamicListActivity;
import com.onenine.app.activity.GreetListMsgActivity;
import com.onenine.app.activity.GroupMessageActivity;
import com.onenine.app.activity.MyContactActivity;
import com.onenine.app.activity.PraiseListActivity;
import com.onenine.app.activity.PrivateMessageActivity;
import com.onenine.app.activity.ReplyListActivity;
import com.onenine.app.activity.SystemMsgListActivity;
import com.onenine.app.db.DataManager;
import com.onenine.app.event.MessageNotifyEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.response.UserInfoResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.SpCommonHelper;
import com.onenine.base.base.BaseEventFragment;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.SimpleToolbar;
import com.onenine.chat.commons.IConversation;
import com.onenine.chat.conversation.ConversationList;
import com.onenine.chat.conversation.ConversationListAdapter;
import com.onenine.chat.model.LConversation;
import com.onenine.chat.rongcloud.RcConnector;
import com.onenine.chat.rongcloud.RcImMgr;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ActivityUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.message.GroupNotificationMessage;

/**
 * 创建时间：2018/5/30 0030 11:00
 * 创建人：fly
 * 功能描述：会话消息列表
 */
public class MessageFragment extends BaseEventFragment implements ConversationListAdapter.OnDialogClickListener
        , ConversationListAdapter.OnDialogDeleteClickListener, View.OnClickListener {

    private ConversationList mConversationList;
    private ConversationListAdapter mConversationAdapter;
    private IConversation mActiveConversation;
    private SimpleToolbar sToolbar;
    private ImageView mGreetBubble, mPraiseBubble, mReplyBubble, mInviteBubble, mSystemBubble;
    private View mGreetLayout, mPraiseLayout, mReplyLayout, mInviteLayout, mSystemLayout;

    @Override
    protected int getLayout() {
        return R.layout.fragment_message;
    }

    @Override
    protected void initView(View view) {
        sToolbar = view.findViewById(R.id.tb_toolbar);
        sToolbar.setCenterTitle(R.string.message);
        sToolbar.setLeftTitle(R.string.contact_book);
        sToolbar.setBottomDividerVisible(false);
        sToolbar.setRightTitleDrawable(R.drawable.ic_circle_star);
        mConversationList = view.findViewById(R.id.dialog_list);
        mConversationList.setNestedScrollingEnabled(false);
        mConversationAdapter = new ConversationListAdapter();
        mConversationList.setAdapter(mConversationAdapter);
        mGreetBubble = view.findViewById(R.id.iv_greet_bubble);
        mGreetBubble.setImageResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.CIRCLE_POINT_BUBBLE));
        mPraiseBubble = view.findViewById(R.id.iv_praise_bubble);
        mReplyBubble = view.findViewById(R.id.iv_reply_bubble);
        mInviteBubble = view.findViewById(R.id.iv_ask_bubble);
        mSystemBubble = view.findViewById(R.id.iv_system_bubble);
        mGreetLayout = view.findViewById(R.id.ll_new_friend);
        mPraiseLayout = view.findViewById(R.id.ll_praise);
        mReplyLayout = view.findViewById(R.id.ll_reply);
        mInviteLayout = view.findViewById(R.id.ll_ask_invite);
        mSystemLayout = view.findViewById(R.id.ll_system);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mConversationAdapter.setOnDialogClickListener(this);
        mConversationAdapter.setOnDialogDeleteClickListener(this);
        sToolbar.setOnLeftClickListener(this);
        sToolbar.setOnRightClickListener(this);
        mGreetLayout.setOnClickListener(this);
        mPraiseLayout.setOnClickListener(this);
        mReplyLayout.setOnClickListener(this);
        mInviteLayout.setOnClickListener(this);
        mSystemLayout.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (RcConnector.isConnected()) {
            getConversationList();
        }
    }

    @Override
    public void initData() {
        super.initData();
        setGreetBubbleVisible();
    }

    /**
     * 显示打招呼数量
     */
    private void setGreetBubbleVisible() {
        if (!SpCommonHelper.getInstance().isGreetMsgRead()) {
            int count = DataManager.getAllFriendMessageCountByUserId(RcUser.getInstance().getUserId());
            mGreetBubble.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
        } else {
            mGreetBubble.setVisibility(View.GONE);
        }
    }

    /**
     * 获取会话列表
     */
    public void getConversationList() {
        RcImMgr.getInstance().getConversationList(new RcImMgr.OnConversationListener() {
            @Override
            public void onResult(List<LConversation> lConversations) {
                mConversationAdapter.setItems(lConversations);
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Toasty.showNormal("会话加载失败:" + errorCode);
            }
        });
    }

    /**
     * 消息提醒事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageNotifyEvent event) {
        switch (event.type) {
            case DataType.CONNECT_NOTIFY_MSG:
            case DataType.COMMON_NOTIFY_MSG:
                getConversationList();
                break;
            case DataType.GREET_NOTIFY_MSG:
                SpCommonHelper.getInstance().applyGreetMsgRead(false);
                setGreetBubbleVisible();
                break;
        }
    }

    /**
     * 收到退出群后要移除该会话
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GroupNotificationMessage event) {
        if (event == null || !TextUtils.equals(event.getOperation(), GroupNotificationMessage.GROUP_OPERATION_DISMISS)) {
            return;
        }
        List<LConversation> dataList = mConversationAdapter.getItems();
        for (LConversation conv : dataList) {
            if (TextUtils.equals(event.getData(), conv.getTargetId())) {
                mConversationAdapter.delete(conv);
                RcImMgr.getInstance().deleteConversation(conv);
                break;
            }
        }
    }

    /**
     * 清除未读标识
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (mActiveConversation == null) {
            return;
        }
        if (event.getType() != DataType.REFRESH_CLEAR_UNREAD_COUNT) {
            return;
        }
        RcImMgr.getInstance().clearConversationMsgUnreadStatus(mActiveConversation, new RongIMClient.ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean isClear) {
                if (!isClear) {
                    return;
                }
                List<IConversation> dataList = mConversationAdapter.getItems();
                for (int i = 0; i < dataList.size(); i++) {
                    IConversation conversation = dataList.get(i);
                    if (conversation.getTargetId().equals(mActiveConversation.getTargetId())
                            && conversation.getUnreadCount() > 0) {
                        conversation.clearUnreadCount();
                        mConversationAdapter.notifyItemChanged(i);
                        break;
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    @Override
    public void onDialogClick(IConversation iConversation) {
        mActiveConversation = iConversation;
        if (iConversation.getConversationType() == Conversation.ConversationType.PRIVATE) {
            PrivateMessageActivity.launchActivity(getActivity()
                    , iConversation.getTargetId(), iConversation.getConversationTitle());
        } else if (iConversation.getConversationType() == Conversation.ConversationType.GROUP) {
            GroupMessageActivity.launchActivity(getActivity(), iConversation.getTargetId(), iConversation.getConversationTitle());
        }
    }

    @Override
    public void onDialogDeleteClick(View view, IConversation iConversation) {
        mConversationAdapter.delete(iConversation);
        RcImMgr.getInstance().deleteConversation(iConversation);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right_title:
                UserInfoResponse userInfo = RcUser.getInstance().getInfoResponse();
                if (userInfo != null) {
                    DynamicListActivity.launchActivity(getActivity()
                            , RcUser.getInstance().getUserId(), userInfo.getBackgroundPicture());
                } else {
                    DynamicListActivity.launchActivity(getActivity()
                            , RcUser.getInstance().getUserId(), "");
                }
                break;
            case R.id.tv_left_title:
                ActivityUtils.startActivity(getActivity(), MyContactActivity.class);
                break;
            case R.id.ll_new_friend:
                //打招呼
                SpCommonHelper.getInstance().applyGreetMsgRead(true);
                setGreetBubbleVisible();
                ActivityUtils.startActivity(getActivity(), GreetListMsgActivity.class);
                break;
            case R.id.ll_praise:
                //点赞
                ActivityUtils.startActivity(getActivity(), PraiseListActivity.class);
                break;
            case R.id.ll_reply:
                //回复
                ActivityUtils.startActivity(getActivity(), ReplyListActivity.class);
                break;
            case R.id.ll_ask_invite:
                //邀请
                ActivityUtils.startActivity(getActivity(), AskInviteListActivity.class);
                break;
            case R.id.ll_system:
                //系统消息
                ActivityUtils.startActivity(getActivity(), SystemMsgListActivity.class);
                break;
        }
    }

}
